package com.legend.ds.config;


import com.alibaba.druid.pool.DruidDataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @Auther: tangwei
 * @Date: 2021/7/12 下午3:15
 * @Description: 类描述信息
 */
@Slf4j
public class MybatisPlusConfig implements EnvironmentAware {

    private LanzhenDynamicDataSource dynamicDataSource = new LanzhenDynamicDataSource();
    /**
     * 配置上下文（也可以理解为配置文件的获取工具）
     */
    private Environment env;

    /**
     * 参数绑定工具 springboot2.0新推出
     */
    private Binder binder;

    @Override
    public void setEnvironment(Environment environment) {
        log.info("开始注册数据源");

        this.env = environment;
        binder = Binder.get(env);

        Map tenantDSMap = binder.bind("lanzhen.ds.tenant-ds", Map.class).get();
        if(tenantDSMap.size() <= 0){
            log.error("请配置多数据源");
            throw new RuntimeException("请配置多数据源");
        }

        //初始化多数据源
        DataSource defaultTargetDataSource = null;
        Map<Object, Object> targetDataSources = new HashMap<>();
        for (Object key :tenantDSMap.keySet()){
            String tenantNode = (String) key;
            Map tmpMap = (Map)tenantDSMap.get(tenantNode);
            DruidDataSource druidDataSource = new DruidDataSource();
            druidDataSource.setUrl((String) tmpMap.get("url"));
            druidDataSource.setDriverClassName((String) tmpMap.get("driver-class-name"));
            druidDataSource.setDbType((String)tmpMap.get("type"));
            druidDataSource.setUsername((String)tmpMap.get("username"));
            druidDataSource.setPassword(String.valueOf(tmpMap.get("password")));
            targetDataSources.put(tenantNode, druidDataSource);
            log.info("数据源" + tenantNode +"初始化完毕");

            if(defaultTargetDataSource == null && tenantNode.equals("default")){
                defaultTargetDataSource = druidDataSource;
            }
        }
        dynamicDataSource.setTargetDataSources(targetDataSources);
        dynamicDataSource.setDefaultTargetDataSource(defaultTargetDataSource);
    }

    /**
     * 动态数据源配置
     *
     * @return
     */
    @Bean
    @Primary
    public DataSource multipleDataSource() { //这个方法主要是确定系统中数据源的切换器
        return this.dynamicDataSource;
    }
}


